import { NextResponse } from "next/server";
import { listCommentsByPathname, createComment } from "@/app/utils/db";
import { getTokenFromRequest, verifyToken } from "@/app/utils/auth";

export const runtime = 'nodejs';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const pathname = searchParams.get("pathname");
  if (!pathname) {
    return NextResponse.json({ error: "pathname is required" }, { status: 400 });
  }
  const comments = listCommentsByPathname(pathname).map(row => ({
    id: row.id,
    pathname: row.pathname,
    content: row.content,
    createdAt: row.created_at,
    user: {
      id: row.user_id,
      email: row.user_email,
      displayName: row.user_display_name,
    },
  }));
  return NextResponse.json({ comments }, { status: 200 });
}

export async function POST(request) {
  try {
    const token = getTokenFromRequest(request);
    const payload = token ? verifyToken(token) : null;
    if (!payload?.sub) {
      return NextResponse.json({ error: "unauthorized" }, { status: 401 });
    }
    const body = await request.json();
    const { pathname, content } = body || {};
    if (!pathname || !content) {
      return NextResponse.json({ error: "pathname and content are required" }, { status: 400 });
    }
    const created = createComment({ pathname, userId: payload.sub, content });
    return NextResponse.json({ id: created.id }, { status: 201 });
  } catch (e) {
    return NextResponse.json({ error: "invalid request", detail: String(e?.message || e) }, { status: 400 });
  }
}


